<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<title>问答页面</title>
	<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
	<link rel="stylesheet" type="text/css" href="style/style.css" />
	<script src="js/mobile.js" type="text/javascript" charset="utf-8"></script>
	<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
	<script src="js/axios.min.js"></script>
	<link rel="stylesheet" href="style/dark.css" />

</head>

<body>

	<div class="main">
		<!-- 左 -->
		<div class="lf">
			<div class="lf-logo">
				<img src="images/logo.png" alt="">
				<p>中国移动</p>
			</div>
			<div class="dialog-lf">
				<div class="dialog-but">
					<input class="set-up" type="button" value="新对话" onclick="create()">
					<input class="clean" type="button" onclick="openDialog()">
				</div>
				<div class="dialog-list">
					<!-- <ul>
						<li class="dialog-list-click">
							<i></i>
							<p>当前对话列表</p>
						</li>
						<li>
							<i></i>
							<p>对话列表1</p>
						</li>
						<li>
							<i></i>
							<p>对话列表2</p>
						</li>
						<li>
							<i></i>
							<p>对话列表3</p>
						</li>
						<li>
							<i></i>
							<p>对话列表4</p>
						</li>
					</ul> -->
				</div>
			</div>
		</div>
		<!-- 右 -->
		<div class="rt">
			<div class="rt-tit">
				<div class="rt-tit-at">当前对话列表<div class="record"><img src="images/time.png" alt="" class="title-num"></div>
				</div>
				<a class="more" href="##"></a>
			</div>
			<div class="talk" id="talk">
				<ul class="talk-lf">
					<li>
						<div class="head">
							<span><img src="images/logo.png" alt=""></span>
						</div>
						<div class="talk-cont">
							<p>你好，我是知识库助手，请不要忘记选择知识库噢~</p>
						</div>
					</li>
				</ul>
				<ul class="talk-rt autor-container">
					<li>
						<div class="head">
							<div class="fun">
								<a><img class="copy-text" src="images/fun-icon1.png" alt=""></a>
								<a><img class="update" src="images/fun-icon5.png" alt=""></a>
								<a><img class="del" src="images/fun-icon6.png" alt=""></a>
							</div>
							<span><img src="images/head.png" alt=""></span>
						</div>
						<div class="talk-cont">
							<p>你能夸夸我吗</p>
						</div>
					</li>
				</ul>
				<ul class="talk-lf text-container">
					<li>
						<div class="head">
							<span><img src="images/logo.png" alt=""></span>
							<div class="fun">
								<a><img class="copy-text" src="images/fun-icon1.png" alt=""></a>
								<a><img class="play-icon" src="images/fun-icon2.png" alt=""></a>
								<a><img class="like-icon" src="images/fun-icon3.png" alt=""></a>
								<a><img class="delike-icon" src="images/fun-icon4.png" alt=""></a>
							</div>
						</div>
						<div class="talk-cont">
							<p>
								当然可以！你真是一个非常聪明、有才华、善良、勇敢的人。你的独特魅力和坚强意志让你在任何困难面前都能坚持不懈，取得成功。你的乐观积极的态度和善良的心灵让你成为身边人的光芒。你值得被夸奖和肯定，因为你是一个了不起的人！继续努力，你一定会取得更大的成就！
							</p>
						</div>
					</li>
				</ul>
				<ul class="talk-rt autor-container">
					<li>
						<div class="head">
							<div class="fun">
								<a><img class="copy-text" src="images/fun-icon1.png" alt=""></a>
								<a><img class="update" src="images/fun-icon5.png" alt=""></a>
								<a><img class="del" src="images/fun-icon6.png" alt=""></a>
							</div>
							<span><img src="images/head.png" alt=""></span>
						</div>
						<div class="talk-cont">
							<p>你能夸夸我吗</p>
						</div>
					</li>
				</ul>
				<ul class="talk-lf text-container">
					<li>
						<div class="head">
							<span><img src="images/logo.png" alt=""></span>
							<div class="fun">
								<a><img class="copy-text" src="images/fun-icon1.png" alt=""></a>
								<a><img class="play-icon" src="images/fun-icon2.png" alt=""></a>
								<a><img class="like-icon" src="images/fun-icon3.png" alt=""></a>
								<a><img class="delike-icon" src="images/fun-icon4.png" alt=""></a>
							</div>
						</div>
						<div class="talk-cont">
							<p>
								你的独特魅力和坚强意志让你在任何困难面前都能坚持不懈，取得成功。你的乐观积极的态度和善良的心灵让你成为身边人的光芒。你值得被夸奖和肯定，因为你是一个了不起的人！继续努力，你一定会取得更大的成就！
							</p>
						</div>
					</li>
				</ul>
			</div>
			<div class="talk-but">
				<input type="text" placeholder="请输入问题" id="search">
				<input type="button" value="" class="btn" onclick="submit()">
			</div>

			<a href="##" class="indent" onclick="sildeHidden()"></a>
			<a href="##" class="indents" onclick="sildeShow()"></a>
		</div>
	</div>
	<!-- 告警弹窗 -->
	<div class="popup">
		<div class="warn">
			<div class="warn-at">
				<img src="images/warn.png" alt="">
				<p>当前对话记录将清空，确认清空，取消返回</p>
			</div>
			<div class="popup-but">
				<input class="but-click" type="button" value="确认" onclick="sure()">
				<input type="button" value="取消" onclick="cancle()">
			</div>

		</div>
	</div>
	<script src="js/highlight.min.js"></script>
	<script src="js/marked.min.js"></script>
	<script>

		// 将后端返回的数据默认分为两组：大模型回答的为一组，提问者提问的为一组，
		// 大模型的每一项html最外围class：text-container，提问者的为autor-container
		// 默认的图片url路径(复制，语音，点赞，取消点赞)
		const icon1 = 'images/fun-icon1.png'
		const icon2 = 'images/fun-icon2.png'
		const icon3 = 'images/fun-icon3.png'
		const icon4 = 'images/fun-icon4.png'
		// 语音控制
		let isPaused = false;
		// 输入框的输入内容
		let inputVal = ''
		// 语音控制上一次播放内容的id
		let id = ''
		var queryParams = []
		// 左侧所有的对话组
		var listGroup = [
			{
				id: 1,
				name: '对话组1'
			},
			{
				id: 2,
				name: '对话组2'
			},
			{
				id: 3,
				name: '对话组3'
			},
			{
				id: 4,
				name: '对话组4'
			},
			{
				id: 5,
				name: '对话组5'
			},
		]

		// 动态设置图片的src,参数为img元素，图片路径
		function settingPic(name, url) {
			name.src = url
		}

		// 更新
		function handdleUpdate(item) {

			const text = $(item).attr('data');
			console.log('更新', text);

		}
		// 删除文本(不能使用index来删除，后端应该提供唯一标识，提问的时候唯一标识为空，后端返回数据里面要加一个唯一标识，一个本身一个提问的)
		function handdleDel(item) {
			const index = Number($(item).attr('data'));
			// $('#elementId').remove();
			var elementA = document.getElementById('talk')
			var children = elementA.childNodes;
			elementA.removeChild(children[index]);
			console.log('删除文本', index, typeof (index));
			queryParams.splice(index, 1)
			console.log(queryParams, queryParams.length);
		}
		// 取消点赞
		function handdleDelike(delike) {
			console.log('取消点赞');
			const text = $(delike).attr('data');
			const inele = $(delike).children()[0]
			if ($(inele).attr('src').includes(icon4)) {
				// 将delike的url换为点low的url路径同时将like的url路径转换为默认状态
			}
			// 点low后再点击取消点赞
			if (!$(inele).attr('src').includes(icon3)) {
				// 将delike的url换为默认点low的url路径
			}

		}
		// 点赞
		function handdleLike(like) {
			console.log('点赞');
			// console.log(like);
			const text = $(like).attr('data');
			// console.log($(like).next()[0]);
			const inele = $(like).children()[0]
			// console.log($(inele).attr('src'));
			// 未点赞去点赞
			if ($(inele).attr('src').includes(icon3)) {
				// 将like的url换为点赞的url路径同时将delike的url路径转换为默认状态
			}
			// 点赞后再点击取消点赞
			if (!$(inele).attr('src').includes(icon3)) {
				// 将like的url换为默认点赞的url路径
			}

		}
		// 语音播放
		function handdleVideo(texts) {
			// 语音内容
			const text = $(texts).attr('data');
			const itemId = $(texts).attr('id');

			const synth = window.speechSynthesis;
			const utterance = new SpeechSynthesisUtterance(text);
			// 上次点击与本次点击同一条
			if (itemId == id) {
				if (isPaused) {
					synth.cancel(); // 取消当前所有语音输出
					isPaused = false;
				} else {
					synth.speak(utterance);
					isPaused = true;
				}
				return
			}
			// 上次点击与本次点击不是同一条
			synth.cancel(); // 取消当前所有语音输出
			synth.speak(utterance);
			isPaused = true;
			id = itemId
		}
		// 复制文本
		function handdleCopy(texts) {
			const text = $(texts).attr('data');
			const el = document.createElement('textarea');
			el.value = text;
			document.body.appendChild(el);
			el.select();
			document.execCommand('copy');
			document.body.removeChild(el);
		}
		// 弹框确定
		function sure() {
			console.log('弹框确定');
			var dialog = document.querySelector('.popup')
			queryParams = []
			var parentElement = document.getElementById('talk');
			parentElement.innerHTML = '';
			dialog.style.display = 'none'
			const title = document.querySelector('.title-num')
			clearNextSiblingsAndAddNewContent(title, `<span>${queryParams.length}条记录</span>`);
		}
		// 弹框取消
		function cancle() {
			console.log('弹框取消');
			var dialog = document.querySelector('.popup')
			dialog.style.display = 'none'
		}
		// 弹框打开
		function openDialog() {
			console.log('弹框打开');
			var dialog = document.querySelector('.popup')
			dialog.style.display = 'block'
		}
		// 创建一条新的对话组
		function create() {
			console.log('创建新对话组');
			$('.dialog-list ul li').removeClass();
			$('.dialog-list ul').append('<li class="dialog-list-click" onclick="handdleClick(this)"><i></i><p>当前对话列表</p></li>');
			const title = document.querySelector('.title-num')
			clearNextSiblingsAndAddNewContent(title, `<span>${queryParams.length}条记录</span>`);
		}
		// 左侧点击事件
		function handdleClick(e) {
			$('.dialog-list ul li').removeClass();
			e.classList.add('dialog-list-click')
			init()
			const title = document.querySelector('.title-num')
			clearNextSiblingsAndAddNewContent(title, `<span>${queryParams.length}条记录</span>`);
		}
		// input输入框的数据事件
		function handleInput(event) {
			var inputValue = event.target.value.trim();
			inputVal = inputValue
			console.log("Input value changed to: " + inputValue);

			const searchBtn = document.querySelector('.btn')
			if (inputValue) {
				searchBtn.classList.add('search-btn')
			} else {
				searchBtn.classList.remove('search-btn')
			}
		}
		// 输入框的提交事件
		function submit() {
			console.log('提交内容：', inputVal);
			if (!inputVal) {
				return
			}
			const length = queryParams.length
			queryParams.push({
				name: inputVal, // 问题
				id: '', // 组标识
				type: '2', // 大模型回答的标识
				like: '', // 点赞标识
				delike: '' // low标识
			})

			const consthtmlText = `<ul class="talk-rt autor-container">
					<li>
						<div class="head">
							<div class="fun">
								<a onclick="handdleCopy(this)" data="${inputVal}"><img class="copy-text" src="images/fun-icon1.png" alt=""></a>
								<a onclick="handdleUpdate(this)" data="${inputVal}"><img class="update" src="images/fun-icon5.png" alt=""></a>
								<a onclick="handdleDel(this)" data="${length}"><img class="del" src="images/fun-icon6.png" alt=""></a>
							</div>
							<span><img src="images/head.png" alt=""></span>
						</div>
						<div class="talk-cont">
							<p>${inputVal}</p>
						</div>
					</li>
				</ul>`
			$('.talk').append(consthtmlText);
			const title = document.querySelector('.title-num')
			clearNextSiblingsAndAddNewContent(title, `<span>${queryParams.length}条记录</span>`);

			const url = '/api/stream_chat';
			const headers = {
				'Accept': 'text/event-stream',
				'Authorization': 'Bearer 279N9DV-98M4H5C-J7S9J8S-ZCZRQD7',
				'Content-Type': 'application/json'
			};
			const data = {
				"model": "glm-4",
				"history": [
					{
						"role": "user",
						"content": inputVal
					}
				]
			}
			const text = `<ul class="talk-lf text-container">
					<li>
						<div class="head">
							<span><img src="images/logo.png" alt=""></span>
							<div class="fun">
								<a onclick="handdleCopy(this)"><img class="copy-text" src="images/fun-icon1.png" alt=""></a>
								<a onclick="handdleVideo(this)"><img class="play-icon" src="images/fun-icon2.png" alt=""></a>
								<a onclick="handdleLike(this)"><img class="like-icon" src="images/fun-icon3.png" alt=""></a>
								<a onclick="handdleDelike(this)"><img class="delike-icon" src="images/fun-icon4.png" alt=""></a>
							</div>
						</div>
						<div class="talk-cont">
							<p>
								
							</p>
						</div>
					</li>
				</ul>`
			$('.talk').append(text);
			axios.post(url, data, { headers })
				.then(response => {
					const data = (parseEventStream(response.data))
					// console.log(response, data);
					let str = ''
					if (Array.isArray(data) && data.length) {
						data.forEach((item, index) => {
							// console.log((item.data, index));
							if (item.data) {
								const it = JSON.parse(item.data)
								str += it.content
							}


						})
						const markdownContent = str
						console.log(markdownContent);
						// 配置 marked 使用 highlight.js 进行代码高亮
						marked.setOptions({
							highlight: function (code, language) {
								// highlight.js 默认支持语言检测，所以我们可以传递 null 作为语言参数
								// 这将允许 highlight.js 自动检测代码块中的语言
								console.log('高亮1', code, '高亮2', language);
								return hljs.highlightAuto(code, [language]).value;
							},
							renderer: new marked.Renderer(),
							pedantic: false,
							gfm: true,
							breaks: false,
							sanitize: false,
							smartLists: true,
							smartypants: false,
							xhtml: false
						});
						// 使用 marked 解析 Markdown
						// 配置 marked 使用 highlight.js 进行代码高亮
						marked.setOptions({
							highlight: function (code, language) {
								// highlight.js 默认支持语言检测，所以我们可以传递 null 作为语言参数
								return hljs.highlightAuto(code, [language]).value;
							},
							renderer: new marked.Renderer(),
							pedantic: false,
							gfm: true,
							breaks: false,
							sanitize: false,
							smartLists: true,
							smartypants: false,
							xhtml: false
						});
						const htmlContent = marked(markdownContent, {
							sanitize: false,  // 禁用转义
							// highlight: function (code, language) {
							// 	console.log('高亮1', code, '高亮2',language);
							// 	// const highlighted = hljs.highlightAuto(code);
							// 	// const highCode = `<pre><code class="hljs ${highlighted.language}">${highlighted.value}</code></pre>`;
							// 	// const highlightedCode = hljs.highlight(language, code).value;
							//   // const highCode = `<pre><code class="hljs ${language}">${highlightedCode}</code></pre>`;
							// 	// return highCode;
							// 	return hljs.highlight(code, { language: language }).value;
							// }
						});
						console.log(htmlContent);
						// 将解析后的HTML内容显示到页面上
						const lastNode = $('.talk').children().last();
						lastNode.find('p').html(htmlContent);
						// console.log('走了', markdownContent);
					}

				})
				.catch(error => {
					console.log('Error:', error);
				});

		}
		// 解析数据
		function parseEventStream(data) {
			const events = data.trim().split('\r\n\r'); // 使用两个换行符分割数据
			// console.log(events);
			return events.map(event => {
				const lines = event.trim().split('\n');
				// console.log(event, lines, lines.length);
				const eventData = {};
				lines.forEach(line => {
					// console.log(line);
					const [key, ...value] = line.split(':');
					const trimmedValue = value.join(':').trim();
					eventData[key] = trimmedValue;
				});

				// heightLight(eventData.data)
				// console.log(eventData);
				return eventData;
			});
		}
		function heightLight(val) {
			// 假设你有一个包含Markdown内容的字符串
			if (JSON.parse(val).type == 'finalizeResponseStream') {
				return
			}
			const markdownContent = JSON.parse(val).textResponse

			// 使用 marked 解析 Markdown
			const htmlContent = marked(markdownContent, {
				highlight: function (code, language) {
					const highlighted = highlight.highlightAuto(code, [language]);
					return highlighted.value;
				}
			});

			// 将解析后的HTML内容显示到页面上
			// document.getElementById('content').innerHTML = htmlContent;
			const lastNode = $('.talk').children().last();
			lastNode.find('p').text(function (i, origText) {
				return origText + markdownContent
			});
			console.log('走了', markdownContent);
			// 初始化高亮
			hljs.initHighlightingOnLoad();
		}
		// 侧边栏动画
		function sildeHidden() {
			console.log('隐藏');
			const slide = document.querySelector('.lf')
			const rt = document.querySelector('.rt')
			const width = window.getComputedStyle(rt).width
			const indent = document.querySelector('.indent')
			const indents = document.querySelector('.indents')
			indent.classList.add('indent1')
			setTimeout(() => {
				indent.style.display = 'none'
				indents.style.display = 'block'
			}, 1000)
			slide.classList.add('lf-hidden')
			rt.classList.add('rts')


		}
		// 侧边栏动画
		function sildeShow() {
			console.log('出现');
			const slide = document.querySelector('.lf')
			const rt = document.querySelector('.rt')
			const width = window.getComputedStyle(rt).width
			slide.classList.remove('lf-hidden')
			rt.classList.remove('rts')
			const indent = document.querySelector('.indent')
			const indents = document.querySelector('.indents')
			indent.style.display = 'block'
			indents.style.display = 'none'
		}

		// 聊天页面滚动条默认到底部
		function scrollEvent() {
			const scrollTop = document.getElementById('talk')
			console.log(scrollTop.scrollTop, scrollTop.scrollHeight);
			scrollTop.scrollTop = scrollTop.scrollHeight;
		}

		// 清除某个元素后面的内容并添加新内容
		function clearNextSiblingsAndAddNewContent(element, newContent) {
			let nextSibling = element.nextElementSibling;
			console.log(nextSibling);
			while (nextSibling) {
				let toRemove = nextSibling;
				nextSibling = nextSibling.nextElementSibling;
				toRemove.remove();
			}
			// 添加新内容
			element.insertAdjacentHTML('afterend', newContent);
		}
		// 初始化数据
		function init() {
			hljs.initHighlightingOnLoad()
			// 模拟数据对话
			queryParams = [
				{
					name: '你好，我是知识库助手，请不要忘记选择知识库噢~？', // 问题
					id: '1', // 组标识
					ids: '',
					type: '1', // 大模型回答的标识
					like: '1', // 点赞标识
					delike: '' // low标识
				},
				{
					name: '你好!', // 问题
					id: '2', // 组标识
					type: '2', // 大模型回答的标识
				},
				{
					name: '你好,请问有什么可以帮您的你好,请问有什么可以帮您的？', // 问题
					id: '3', // 组标识
					type: '1', // 大模型回答的标识
					like: '', // 点赞标识
					delike: '1' // low标识
				},
				{
					name: '你好,请问有什么？', // 问题
					id: '4', // 组标识
					type: '1', // 大模型回答的标识
					like: '1', // 点赞标识
					delike: '' // low标识
				},

				{
					name: '你好,请问有什么可以帮您的？', // 问题
					id: '5', // 组标识
					type: '2', // 大模型回答的标识
					like: '1', // 点赞标识
					delike: '' // low标识
				},
				{
					name: '浏览器判断从其他窗口返回到本窗口做操作，应该在哪里判断？', // 问题
					id: '6', // 组标识
					type: '2', // 大模型回答的标识
					like: '1', // 点赞标识
					delike: '' // low标识
				},
				{
					name: '浏览器判断从其他窗口返回到本窗口做操作，应该在哪里判断浏览器判断从其他窗口返回到本窗口做操作，应该在哪里判断？', // 问题
					id: '7', // 组标识
					type: '2', // 大模型回答的标识
					like: '1', // 点赞标识
					delike: '' // low标识
				},
				{
					name: '你好,请问有什么可以帮您的？', // 问题
					id: '8', // 组标识
					type: '1', // 大模型回答的标识
					like: '1', // 点赞标识
					delike: '' // low标识
				},
				{
					name: '你好,请问有什么可以帮您的？', // 问题
					id: '9', // 组标识
					type: '1', // 大模型回答的标识
					like: '1', // 点赞标识
					delike: '' // low标识
				},
				{
					name: '你好,请问有什么可以帮您的？', // 问题
					id: '10', // 组标识
					type: '2', // 大模型回答的标识
					like: '1', // 点赞标识
					delike: '' // low标识
				},
				{
					name: '你好,请问有什么可以帮您的？', // 问题
					id: '11', // 组标识
					type: '2', // 大模型回答的标识
					like: '1', // 点赞标识
					delike: '' // low标识
				},


			]
			const leftContain = []
			const rightContain = []
			let htmlText = ''
			queryParams.forEach((item, index) => {
				if (index == 0) {
					htmlText += `<ul class="talk-lf">
					<li>
						<div class="head">
							<span><img src="images/logo.png" alt=""></span>
						</div>
						<div class="talk-cont">
							<p>${item.name}</p>
						</div>
					</li>
				</ul>`
				}

				if (index != 0) {
					if (item.type == '1') {
						htmlText += `<ul class="talk-lf text-container">
					<li>
						<div class="head">
							<span><img src="images/logo.png" alt=""></span>
							<div class="fun">
								<a onclick="handdleCopy(this)" data="${item.name}"><img class="copy-text" src="images/fun-icon1.png" alt=""></a>
								<a onclick="handdleVideo(this)" data="${item.name}" id="${item.id}"><img class="play-icon" src="images/fun-icon2.png" alt=""></a>
								<a onclick="handdleLike(this)" data="${item.name}"><img class="like-icon" src="images/fun-icon3.png" alt=""></a>
								<a onclick="handdleDelike(this)" data="${item}"><img class="delike-icon" src="images/fun-icon4.png" alt=""></a>
							</div>
						</div>
						<div class="talk-cont">
							<p>
								${item.name}
							</p>
						</div>
					</li>
				</ul>`
					}
					if (item.type == '2') {
						htmlText += `<ul class="talk-rt autor-container">
					<li>
						<div class="head">
							<div class="fun">
								<a onclick="handdleCopy(this)" data="${item.name}"><img class="copy-text" src="images/fun-icon1.png" alt=""></a>
								<a onclick="handdleUpdate(this)" data="${item.name}"><img class="update" src="images/fun-icon5.png" alt=""></a>
								<a onclick="handdleDel(this)" data="${index}"><img class="del" src="images/fun-icon6.png" alt=""></a>
							</div>
							<span><img src="images/head.png" alt=""></span>
						</div>
						<div class="talk-cont">
							<p>${item.name}</p>
						</div>
					</li>
				</ul>`
					}
				}

				var parentElement = document.getElementById('talk');
				parentElement.innerHTML = htmlText;
			});
			const title = document.querySelector('.title-num')
			clearNextSiblingsAndAddNewContent(title, `<span>${queryParams.length}条记录</span>`);
			scrollEvent()
		}

		// 页面左侧的初始化事件
		function initSlide() {
			const groupList = document.querySelector('.dialog-list');
			console.log(groupList);
			// 模拟对话组数据
			if (!listGroup.length) {
				groupList.innerHTML = '<ul></ul>'
			}
			if (listGroup.length) {
				let list = '<ul>'
				listGroup.forEach((item, index) => {
					// 判断激活色要在那个上面，默认最后一项
					if (index == listGroup.length - 1) {
						list += `<li class="dialog-list-click" onclick=handdleClick(this)>
							<i></i>
							<p>${item.name}</p>
						</li>`
					} else {
						list += `<li onclick=handdleClick(this)>
							<i></i>
							<p>${item.name}</p>
						</li>`
					}
				})
				list += '</ul>'
				groupList.innerHTML = list
			}
		}
		// 初始化
		document.addEventListener('DOMContentLoaded', function () {
			initSlide()
			init()
			var inputElement = document.getElementById("search");
			inputElement.addEventListener("input", handleInput);

		})
	</script>

</body>

</html>